package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 分类管理
 */
@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public R<Page<Category>> findByPage(Integer page, Integer pageSize) {
        Page<Category> categoryPage = categoryService.findByPage(page, pageSize);
        return R.success(categoryPage);
    }

    @PostMapping
    public R<String> save(@RequestBody Category category, HttpSession session) {
        Employee userLogin = (Employee) session.getAttribute("userLogin");
        category.setCreateUser(userLogin.getId());
        category.setUpdateUser(userLogin.getId());categoryService.save(category);
        return R.success("添加成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category, HttpSession session) {
        Employee userLogin = (Employee) session.getAttribute("userLogin");
        category.setUpdateUser(userLogin.getId());
        categoryService.update(category);
        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.delete(id);
        return R.success("删除成功");
    }
    @GetMapping("/list")
    public R<List<Category>> findByType(Integer type){
        List<Category> byType = categoryService.findByType(type);
        return R.success(byType);
    }
}
